import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_play_android/ui/base/base_widget.dart';
import 'package:image_picker/image_picker.dart';

class ImagePickerScreen extends BaseWidget {
  const ImagePickerScreen({Key? key}) : super(key: key);

  @override
  BaseWidgetState<BaseWidget> attachState() => ImagePickerState();
}

class ImagePickerState extends BaseWidgetState {
  @override
  AppBar? attachAppBar() => AppBar(title: const Text("图片选择"));

  String? _imagePath;

  final ImagePicker _imagePicker = ImagePicker();

  @override
  void initState() {
    showContent();
    super.initState();
  }

  @override
  Widget attachContentWidget(BuildContext context) {
    return Column(
      children: [
        Container(
          height: 80,
          child: TextButton(onPressed: _takePhoto, child: const Text("拍照")),
          alignment: Alignment.center,
        ),
        Container(
          height: 80,
          child: TextButton(onPressed: _openGallery, child: const Text("相册选择")),
          alignment: Alignment.center,
        ),
        Expanded(child: _imagePickerViewer())
      ],
    );
  }

  void _takePhoto() async {
    XFile? file = await _imagePicker.pickImage(source: ImageSource.camera);
    setState(() {
      _imagePath = file?.path;
    });
  }

  void _openGallery() async {
    XFile? file = await _imagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _imagePath = file?.path;
    });
  }

  Widget _imagePickerViewer() {
    return _imagePath?.isNotEmpty == true
        ? Image.file(File(_imagePath!))
        : const Text("请拍摄或选择一张图片");
  }

  @override
  void onClickErrorWidget() {}
}
